/**
 * @author Eddie
 * @date 2023-10-12
 * 本义 数据中心项目
 */

const Koa = require('koa');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const { koaBody } = require('koa-body');
const static = require('koa-static');
const corn = require('./middleware/cron.js');

const app = new Koa();
app.use(koaBody({ multipart: true }));

/**
 * 路由相关
 */ 
const api_temperature = require('./router/api_temperature');
// 课程相关（康复课程、康乐活动）
const api_class = require('./router/api_class');
// 营养膳食
const api_food = require('./router/api_food');
// 长者风采
const api_zzfc = require('./router/api_zzfc.js');
// 值班
const api_zb = require('./router/api_zb.js');

const api_bracelet = require('./router/api_bracelet.js');


const api_qinglei = require('./router/api_qinglei');
const api_roomList= require('./router/api_roomList');
const api_hujiao=require('./router/api_hujiao');
onerror(app);


app.listen(5058, () => {
  console.log('应用已经启动，端口：5058');
})


// middlewares
app.use(
  bodyparser({
    jsonLimit: '5mb', // 控制body的parse转换大小 default 1mb
  })
);

app.use(async (ctx, next) => {
  // 允许跨域的域名，* 代表所有域名都可以跨域访问
  ctx.set('Access-Control-Allow-Origin', '*');
  // 允许的请求方法
  ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  // 允许的请求头字段
  ctx.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');

  if (ctx.method === 'OPTIONS') {
    // 处理预检请求，直接返回 204 状态码，表示允许跨域访问
    ctx.status = 204;
  } else {
    // 继续处理正常请求
    await next();
  }
});

// 设置静态资源文件夹的路径
app.use(static(__dirname + '/images'));

// routes
app.use(api_temperature.routes(), api_temperature.allowedMethods());
app.use(api_class.routes(), api_class.allowedMethods());
app.use(api_food.routes(), api_food.allowedMethods());
app.use(api_zzfc.routes(), api_zzfc.allowedMethods());
app.use(api_zb.routes(), api_zb.allowedMethods());
app.use(api_qinglei.routes(), api_qinglei.allowedMethods());
app.use(api_roomList.routes(),api_roomList.allowedMethods());
app.use(api_hujiao.routes(),api_hujiao.allowedMethods());
app.use(api_bracelet.routes(),api_bracelet.allowedMethods());

console.log("currentENV:", app.env);

app.on('error', (err, ctx) => {
  console.error('server error', err, ctx);
});

module.exports = app;
